package com.schoolvisitors.service;

import com.schoolvisitors.entity.InstrumentSubType;
import com.schoolvisitors.exception.BusinessException;
import com.schoolvisitors.repository.InstrumentRepository;
import com.schoolvisitors.repository.InstrumentSubTypeRepository;
import com.schoolvisitors.response.ResultCode;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class InstrumentSubTypeService {

    private final InstrumentSubTypeRepository repository;
    private final InstrumentService instrumentService;
    private final InstrumentRepository instrumentRepository;

    public InstrumentSubTypeService(InstrumentSubTypeRepository repository, InstrumentService instrumentService, InstrumentRepository instrumentRepository) {
        this.repository = repository;
        this.instrumentService = instrumentService;
        this.instrumentRepository = instrumentRepository;
    }

    public List<InstrumentSubType> getAll() {
        return repository.findAllByDeleteFalse();
    }

    public Optional<InstrumentSubType> findById(Long id) {
        return repository.findByIdAndDeleteFalse(id);
    }

    public void create(InstrumentSubType subType) {
        repository.save(subType);
    }

    public void deleteById(Long id) {
        InstrumentSubType instrumentSubType = repository.findById(id).orElse(null);

        if (instrumentSubType != null) {
            if (instrumentRepository.existsBySubType(instrumentSubType)){
                throw new BusinessException(ResultCode.INSTRUMENT_SUB_TYPE_HAS_INSTRUMENT);
            }
            instrumentSubType.setDelete(true);
            repository.save(instrumentSubType);
        }
    }
}
